package com.nintendo.frame;

import com.nintendo.entity.pojo.Order;
import com.nintendo.mapper.OrderDao;
import com.nintendo.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import javax.swing.*;
import java.awt.*;

public class OrderDetailFrame extends JFrame {

    private Order order;
    private CheckOutFrame checkOutFrame;
    public OrderDetailFrame(Order order) {
        this.order = order;
        this.checkOutFrame = new CheckOutFrame();
        setTitle("订单详情");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        initUI();
        setVisible(true);
    }

    private void initUI() {
        JPanel panel = new JPanel(new GridLayout(7, 2));

        panel.add(new JLabel("订单号:"));
        panel.add(new JLabel(order.getOrderNo()));
        panel.add(new JLabel("餐桌号:"));
        panel.add(new JLabel(order.getDeskId().toString()));

        panel.add(new JLabel("客户名称:"));
        panel.add(new JLabel(String.valueOf(order.getCustomerid()))); // 假设 Order 类中有 customerName 字段

        panel.add(new JLabel("应收金额:"));
        panel.add(new JLabel(order.getMoney().toString()));

        panel.add(new JLabel("实收金额:"));
        JTextField paidAmountField = new JTextField();
        panel.add(paidAmountField);

        panel.add(new JLabel("找零金额:"));
        JLabel changeLabel = new JLabel("0.0");
        panel.add(changeLabel);

        JButton confirmButton = new JButton("确定");
        confirmButton.addActionListener(e -> {

            try {
                double paidAmount = Double.parseDouble(paidAmountField.getText());
                double change = paidAmount - order.getMoney();
                changeLabel.setText(String.format("%.2f", change));
                // 订单状态改为已支付
                order.setStatus("已支付");
                // 更新订单状态
                SqlSession sqlSession = MyBatisUtils.getSqlSession();
                OrderDao orderMapper = sqlSession.getMapper(OrderDao.class);
                orderMapper.updateByPrimaryKey(order);
                sqlSession.commit();
                // 刷新页面
                CheckOutFrame checkOutFrame = new CheckOutFrame();
                checkOutFrame.refreshTable();
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的金额", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        JButton cancelButton = new JButton("取消");
        cancelButton.addActionListener(e -> dispose());

        panel.add(confirmButton);
        panel.add(cancelButton);

        add(panel);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new OrderDetailFrame(new Order()));
    }
}
